package com.yinxing.webapi.code.service.sys;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.yinxing.framework.exception.OperationException;
import com.yinxing.framework.mybatis.TemplateService;
import com.yinxing.webapi.code.entity.sys.SysDept;
import com.yinxing.webapi.code.viewobje.sys.DeptTreeNode;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

@Slf4j
@Service
@Transactional
public class ISysDeptService extends TemplateService<SysDept> {

    /**
     * 查询全部部门树结构
     */
    public List<DeptTreeNode> selectTreeList() {
        //1:查询全部平级数据
        QueryWrapper<SysDept> wrapper = new QueryWrapper<>();
        List<SysDept> deptList = baseMapper.selectList(wrapper);
        //2:拷贝实体类，改变属性名称
        List<DeptTreeNode> nodeList = this.sysDeptToTreeNode(deptList);
        //3:转换为树结构
        return convertToTreeList(nodeList);
    }

    /**
     * 查询部门树结构(非禁用)
     */
    public List<DeptTreeNode> selectTreeListNoStop() {
        LambdaQueryWrapper<SysDept> qw = new LambdaQueryWrapper<>();
        qw.eq(SysDept::getStop_, false);
        qw.orderByAsc(SysDept::getIndex_);
        List<SysDept> deptList = baseMapper.selectList(qw);
        List<DeptTreeNode> nodeList = this.sysDeptToTreeNode(deptList);
        return convertToTreeList(nodeList);
    }

    /**
     * 转换为EXT所需格式
     * @param deptList 部门列表集合
     */
    public List<DeptTreeNode> sysDeptToTreeNode(List<SysDept> deptList) {
        return deptList.stream().map(dept -> {
            DeptTreeNode node = new DeptTreeNode();
            node.setId(dept.getId_());
            node.setText(dept.getDeptName_());
            node.setDeptCode(dept.getDeptCode_());
            node.setParentId(dept.getParentId_());
            node.setIndex(dept.getIndex_());
            node.setLeaf(dept.getLeaf_());
            node.setStop(dept.getStop_());
            node.setExpanded(dept.getExpanded_());
            node.setExpandedEdit(dept.getExpanded_());
            return node;
        }).collect(Collectors.toList());
    }

    /**
     * 转为树结构
     * @param nodeList 列表结构
     * @return 树结构
     */
    public List<DeptTreeNode> convertToTreeList(List<DeptTreeNode> nodeList) {
        List<DeptTreeNode> rootList = new ArrayList<>();

        //先把全部数据放入Map
        Map<Long, DeptTreeNode> entityMap = new HashMap<>(128);
        for (DeptTreeNode node : nodeList) {
            entityMap.put(node.getId(), node);
        }

        for (DeptTreeNode node : nodeList) {
            //查询父节点-如不存在说明自己是根节点
            DeptTreeNode parentEntity = entityMap.get(node.getParentId());
            if (parentEntity == null) {
                rootList.add(node);
                continue;
            }
            //加入到父亲的子集中
            parentEntity.getChildren().add(node);
        }

        return rootList;
    }

    /**
     * 批量新增|更新
     * @param records ext提交的机构数据格式
     */
    public void insertOrUpdateBatch(List<DeptTreeNode> records) {
        for (DeptTreeNode record : records) {
            SysDept dept = baseMapper.selectById(record.getId());
            if (dept != null) {
                copyValue(dept, record);
                baseMapper.updateById(dept);
            } else {
                dept = new SysDept();
                copyValue(dept, record);
                baseMapper.insert(dept);
            }
        }
    }

    /**
     * 拷贝属性
     * @param dept   机构数据
     * @param record ext数据格式
     */
    private void copyValue(SysDept dept, DeptTreeNode record) {
        dept.setId_(record.getId());
        dept.setParentId_(record.getParentId());
        dept.setLeaf_(record.isLeaf());
        dept.setDeptName_(record.getText());
        dept.setDeptCode_(record.getDeptCode());
        dept.setIndex_(record.getIndex());
        dept.setStop_(record.isStop());
        dept.setExpanded_(record.isExpandedEdit());
        if (dept.getCreateTime_() == null) {
            dept.setCreateTime_(LocalDateTime.now());
        }
    }

    /**
     * 批量删除
     * @param records ext提交的菜单数据集合
     */
    public void deleteBatch(List<DeptTreeNode> records) {
        for (DeptTreeNode record : records) {
            baseMapper.deleteById(record.getId());
        }
    }

    /**
     * 暂停|启用
     * @param id 菜单ID
     */
    public void stopById(long id) {
        SysDept dept = baseMapper.selectById(id);
        if (dept != null) {
            dept.setStop_(!dept.getStop_());
            this.updateById(dept);
        }
    }

    /**
     * 根据部门ID查询部门编码
     * @param id 部门ID
     */
    public String getCodeById(long id) {
        return this.selectByIdRequired(id).getDeptCode_();
    }

    /**
     * 根据部门ID查询部门名称
     * @param id 部门ID
     */
    public String getNameById(long id) {
        return this.selectByIdRequired(id).getDeptName_();
    }

    /**
     * 获取部门信息
     * @param id 部门ID
     */
    public SysDept selectByIdRequired(long id) {
        SysDept dept = baseMapper.selectById(id);
        if (dept != null) {
            return dept;
        }
        throw new OperationException("获取不到部门信息 ID:{" + id + "}");
    }
}